<style lang="scss" scoped>

</style>

<template>
  <el-page-header 
    class=" pl-4 pb-4 border-b"
    @back="router.push({name:'setting'})">
    <template #content>
      <span class="text-large font-600 mr-3"> 上传新数据 </span>
    </template>
  </el-page-header>
  <el-scrollbar 
    class=" p-2"
    height="calc(100vh - 4.5rem)"
  >
    <div
      v-if="!file"
      @click="uploadFile"
      @drop="uploadFile2"
      @dragover="(e)=>{
        e.preventDefault()
      }"
      class=" hover:border-blue-500 cursor-pointer rounded h-40 flex flex-col justify-center items-center border-dotted border">
      <el-icon 
        class=" text-gray-500  "
        size="5rem"
      ><upload-filled /></el-icon>
      <div class=" text-gray-700 ">
        点击选择文件 / 直接拖入 （可选择CSV/EXCEL文件）
      </div>
    </div>
    <template v-else >
      <div class=" flex items-center">
        <p class=" font-bold text-lg mr-4">解析结果</p>
        <el-button
          class=" ml-auto"
          type="danger"
          @click="init()"
        >取消</el-button>
        <el-button
          type="primary"
          @click="opensubmit=true"
        >提交</el-button>
      </div>
      <p class=" bg-black text-white my-2">解析出以下课程：</p>
      <el-scrollbar
        view-class="justify-between p-2 grid gap-2"
        view-style="grid-template-columns: repeat(auto-fill,200px);"
        height="251px"
      >
        <p
          v-for="(item,i) in courses"
          :key="'cou-'+i"
          class=" bg-blue-200 text-center py-1 rounded w-full whitespace-nowrap truncate"
          :title="item"
        >{{item}}</p>
      </el-scrollbar>
      <p class=" bg-black text-white my-2">学生数据:</p>
      <el-scrollbar
        view-class="justify-between p-2 grid gap-2"
        view-style="grid-template-columns: repeat(auto-fill,200px);"
        height="251px"
      >
        <el-popover 
          v-for="item in resdata"
          :key="item['学号']"
          placement="right" 
          :width="400"
          trigger="click"
          :persistent="false"
        >
          <template #reference>
            <p
              class=" cursor-pointer bg-blue-200 text-center py-1 rounded"
            >{{item['姓名']}}</p>
          </template>
          <el-scrollbar 
            view-class=" justify-items-center grid"
            view-style="grid-template-columns: 1fr 40px 1fr;"
            height="80vh">
            <template v-for="(v,k) in item">
              <span class=" w-full truncate">{{k}}</span>
              <span class=" w-full truncate">:</span>
              <span class=" w-full truncate">{{v}}</span>
            </template>
          </el-scrollbar>
        </el-popover>
      </el-scrollbar>
    </template>
  </el-scrollbar>

  <el-dialog v-model="opensubmit" title="Tips" width="80%" draggable>
    <el-input v-model="baseinfo.name" placeholder="输入学生集备注" />
    <el-input
      v-model="baseinfo.desc"
      maxlength="251"
      placeholder="输入描述"
      show-word-limit
      :autosize="{ minRows: 4, maxRows: 8 }"
      type="textarea"
      class=" mt-2"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="opensubmit = false">取消</el-button>
        <el-button type="primary" @click="submit">
          确认提交
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup >
import { useRouter } from "vue-router"
import { UploadFilled } from "@element-plus/icons-vue"
import { reactive, ref, toRefs } from "vue"
import readExcel from "hooks/use_readExcel.js"
import { ElLoading, ElMessage } from "element-plus"
import { syncCourse,syncUser,syncMajor,syncGrade,baseInfoApi } from 'api'
import md5 from 'md5'
import { forIn } from 'lodash' 
const router = useRouter()
const data = reactive({
  file:false,
  resdata:[],
  columns:[],
  courses:[],
  opensubmit:false,
  baseinfo:{
    desc:'',
    name:''
  }
})
let coursesFormatLog = {}
const init = (file,resdata,courses,opensubmit=false,baseinfo={}) => {
  Object.assign(data,{file,resdata,courses,baseinfo,opensubmit})
}

const uploadFile = async () => {
  const upInput = document.createElement("input")
  upInput.type = "file"
  upInput.click()
  upInput.onchange = async (event) => {
    const { path } = event
    const file = path[0].files[0]
    loadFile(file)
  }
}

const uploadFile2 = (e) => {
  e.preventDefault()
  const files = e.dataTransfer.files
  if(files.length > 1)
    ElMessage.error('只能选择一个文件哦')
  const [file] = files
  loadFile(file)
}

const loadFile = async (file) => {
  const load = () => new Promise((ok,no)=>{
    readExcel(file,'Data',({Data})=>{
      if(!Data) {
        ElMessage.error('没有找到Sheet:‘Data’')
        no('匹配失败')
      }
      ok(Data.data)
    })
  })
  const resdata = await load()

  let columns = []
  const courses = Object.keys(resdata[0])
    .filter((e,i)=>{
      const key = `col-${i}`
      columns.push({
        datakey:e,
        key,
        title:e,
        width:150
      })
      return /\[\d+\]/.test(e)
    })
    .map(e=>{
      const v = e.replace(/\[\d+\]/,"")
      coursesFormatLog[e] = v
      return v
    })
  Object.assign(data,{file,resdata,courses,columns})
}

const submit = async () => {
  const { baseinfo:{desc,name},resdata,courses } = data
  if(!desc || !name)
    return ElMessage.error('请补全备注和描述!')
  const courseDict = await syncCourse({courses})
  const majors = Array.from(new Set(resdata.map(({专业:major})=>major)))
  const majorDict = await syncMajor({majors})
  const baseid = await baseInfoApi.post({name,desc})
  const password = md5('84628888')
  const users = resdata.map(
    ({学号:username,姓名:nickname,年级:grade,专业})=>
    ({username,nickname,password,grade,major:majorDict[专业],type:1,baseid})
  )
  const userDict = await syncUser({users})
  const grades = []
  resdata.map(e=>{
    const uid = userDict[e['学号']]
    forIn(e,(grade, key) => {
      if(grade){
        const cid = courseDict[coursesFormatLog[key]]
        grade = Number(grade) || 0
        cid && grades.push({uid,cid,grade})
      }
    })
  })

  await syncGrade({grades})
  setTimeout(()=>{
    ElMessage.success('导入成功')
    router.push({
      name:'setting'
    })
  })
}

const { file,resdata,courses,columns,baseinfo,opensubmit } = { ...toRefs(data) }
</script>